package cn.tedu.controller;

import cn.tedu.util.IPUtils;
import cn.tedu.util.MD5Utils;
import cn.tedu.util.RedisConstant;
import cn.tedu.vo.JsonResult;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Kiven
 */

@RestController
@RequestMapping("/api/v1/captcha")
@Api(tags = {"用户验证码接口"})
public class CaptchaController {



    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Producer producer;


    @RequestMapping("/createCaptcha")
    public void createCaptcha(HttpServletRequest request, HttpServletResponse response){
        //获取验证码内容 ,具体内容在config配置里面可以修改
        String text = producer.createText();
        //根据内容生成图片
        BufferedImage image = producer.createImage(text);

        //把内容存redis ,key设计见底下方法
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request),text,5, TimeUnit.MINUTES);

        ServletOutputStream outputStream =null;
        try {
            outputStream = response.getOutputStream();
            // 写验证码图片至前端
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过验证码校验后进行短信发送
     * @param captcha
     * @param to
     * @param request
     * @return
     */
    @RequestMapping("/send_msg")
    public JsonResult sendMessage(
            @RequestParam(value = "captcha",required=true) String captcha,
            @RequestParam(value = "to",required=true) String to,
            HttpServletRequest request){
        String captchaKey = getCaptchaKey(request);
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(captchaKey);

        //equalsIgnoreCase() 方法用于将字符串与指定的对象比较，不考虑大小写。
        if(captcha != null && cacheCaptcha!=null &&cacheCaptcha.equalsIgnoreCase(captcha)){
            stringRedisTemplate.delete(captchaKey);
            // TODO 发送手机验证码
            return JsonResult.success("发送手机验证码成功");
        }else{
            return JsonResult.fail("发送手机验证码失败");
        }
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ip = IPUtils.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = RedisConstant.USER_CAPTCHA+ MD5Utils.md5(ip+userAgent);
        return key;
    }


}
